package com.ruoyi.planthopper.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.ImageProcessingException;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dataAnalysis.domain.InsectType;
import com.ruoyi.inducement.domain.InducementLog;
import com.ruoyi.inducement.domain.ReturnInducementLog;
import com.ruoyi.inducement.utils.ImageInfoTool;
import com.ruoyi.planthopper.domain.*;
import com.ruoyi.planthopper.mapper.InvestigateMapper;
import com.ruoyi.planthopper.mapper.PlanthopperMapper;
import com.ruoyi.planthopper.service.InvestigateService;

import com.ruoyi.utils.MyDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @program: base-planthopper-detection-master_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2021-09-23 17:31
 **/

@Service
public class InvestigateServiceImpl implements InvestigateService {


    @Autowired
    public InvestigateMapper investigateMapper;

    @Autowired
    public PlanthopperMapper planthopperMapper;

    public ImageInfoTool imageInfoTool;

    /**
     * 插入图片
     * 这里目前先处理一下图片名：diseaseType_shootingTime_meteorological_province_plot_investigator_shootingEquipment.jpg
     * 然后生成图片路径
     * @param investigateInfo
     * @return 返回的是图片路径
     */
    @Override
    public InvestigateInfo insertInvestigateInfo(InvestigateInfo investigateInfo) throws ImageProcessingException, IOException, ParseException {
        //imageInfoTool =new ImageInfoTool();
        //File file = new File("G:\\学习\\研究生\\code\\基部飞虱检测\\2babb390-53d8-420f-9afb-52e9d17a8345__original.jpg");
        //Date uploadTimeDate=imageInfoTool.ImageShootingTimeDate(file);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");



        //String imageName=investigateInfo.getDiseaseType()+"_"+
        //        sdf.format(investigateInfo.getShootingTime())+"_"+
        //        investigateInfo.getWeather() + "_" +
        //        investigateInfo.getWindpower() + "_" +
        //        investigateInfo.getTemperature()+ "_" +
        //        investigateInfo.getHumidity() + "_" +
        //        investigateInfo.getProvince() + "_" +
        //        investigateInfo.getCity() + "_" +
        //        investigateInfo.getDistrict() + "_" +
        //        investigateInfo.getPlot() + "_" +
        //        investigateInfo.getInvestigator() + "_" +
        //        investigateInfo.getShootingEquipment();
        String imageName=investigateInfo.getImagePath().split("/")[investigateInfo.getImagePath().split("/").length-1];
        imageName=imageName.split("__")[0];
        String ImagePathOld=investigateInfo.getImagePath();
        imageName+="__"+ImagePathOld.split("__")[ImagePathOld.split("__").length-1];
        String imagePathOldThum=ImagePathOld.replace("original","thum");
        String imagePathOldResult=ImagePathOld.replace("original","original__Result");
        File oldFile = new File(ImagePathOld);
        File oldFileThum=new File(imagePathOldThum);
        File oldFileResult=new File(imagePathOldResult);

        String path = ImagePathOld.replace(ImagePathOld.split("/")[ImagePathOld.split("/").length-1],"");
        String newImagePath=path+imageName;
        String newImagePathThum=newImagePath.replace("original","thum");
        String newImagePathResult=newImagePath.replace("original","original__Result");
        File newFile = new File(newImagePath);
        File newFileThum=new File(newImagePathThum);
        File newFileResult=new File(newImagePathResult);
        oldFile.renameTo(newFile);
        oldFileThum.renameTo(newFileThum);
        oldFileResult.renameTo(newFileResult);

        newImagePath=newImagePath.replace("\\","/");

        newImagePathThum=newImagePathThum.replace("\\","/");



        //重命名失败，备用手段1，复制该图片，并重命名
        //原因可能是result图片还在被修改，所以有问题
        //检测原因，想要在程序运行中删除图片，他会一直说
        //FileInputStream fin = null;
        //String s=newImagePathResult;
        //FileOutputStream fou = null;
        //byte [] b;
        //int len;

        //b= new byte[1024];
        //fin = new FileInputStream(oldFileResult);
        //fou = new FileOutputStream(s);
        //while((len=fin.read(b)) != -1)
        //{
        //    fou.write(b,0,len);
        //    fou.flush();
        //}
        //fin.close();
        //fou.close();
        //oldFileResult.delete();

        newImagePathResult=newImagePathResult.replace("\\","/");
        investigateInfo.setImagePath(newImagePath);
        investigateInfo.setThumPath(newImagePathThum);
        investigateInfo.setResultPath(newImagePathResult);
        investigateMapper.insertInvestigateInfo(investigateInfo);
        return investigateInfo;

    }

    private TableDataInfo getTableDataInfo(List<InvestigateInfo> investigateInfo, PageInfo<InvestigateInfo> pageInfo) {
        List<ReturnInvestigateInfo> returnInfo = getReturnInfo(investigateInfo);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(returnInfo);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    /**
     * 查询所有调查信息，图片信息
     * @return
     */
    @Override
    public List<ReturnInvestigateInfo> selectInvestigateInfoAll() {

        return getReturnInfo(investigateMapper.selectInvestigateInfoAll());
    }

    /**
     * 查询所有调查信息，图片信息,分页
     * @return
     */
    @Override
    public TableDataInfo selectInvestigateInfoAllPage(Integer pageNum, Integer pageSize) {
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InvestigateInfo> investigateInfos = investigateMapper.selectInvestigateInfoAll();
        PageInfo<InvestigateInfo> pageInfo = new PageInfo<>(investigateInfos);
        return getTableDataInfo(investigateInfos,pageInfo);
    }

    @Override
    public List<ReturnInvestigateInfo> selectInvestigateInfoByConditionMyself(InvestigateInfo investigateInfo) {
        return getReturnInfo(investigateMapper.selectInvestigateInfoByConditionMyself(investigateInfo));
    }

    /**
     * 根据条件查询调查信息（图片信息）
     * @return
     */
    @Override
    public List<ReturnInvestigateInfo> selectInvestigateInfoByCondition(SelectInvestigateInfo selectInvestigateInfo) {
        if(selectInvestigateInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInvestigateInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInvestigateInfo.setEndTime(now.getTime());
        }
        return getReturnInfo(investigateMapper.selectInvestigateInfoByCondition(selectInvestigateInfo));
    }

    /**
     * 根据条件查询调查信息（图片信息）
     * @return
     */
    @Override
    public TableDataInfo selectInvestigateInfoByConditionPage(SelectInvestigateInfo selectInvestigateInfo,Integer pageNum, Integer pageSize) {
        if(selectInvestigateInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInvestigateInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInvestigateInfo.setEndTime(now.getTime());
        }
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InvestigateInfo> investigateInfos = investigateMapper.selectInvestigateInfoByCondition(selectInvestigateInfo);
        PageInfo<InvestigateInfo> pageInfo = new PageInfo<>(investigateInfos);
        return getTableDataInfo(investigateInfos,pageInfo);
    }

    /**
     * 根据条件查询调查人人名
     * @return
     */
    @Override
    public List<String> selectInvestigatorByCondition(SelectInvestigateInfo selectInvestigateInfo) {
        if(selectInvestigateInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInvestigateInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInvestigateInfo.setEndTime(now.getTime());
        }
        return investigateMapper.selectInvestigatorByCondition(selectInvestigateInfo);
    }

    /**
     * 根据条件查询调查地块名
     * @return
     */
    @Override
    public List<String> selectPlotByCondition(SelectInvestigateInfo selectInvestigateInfo) {
        if(selectInvestigateInfo.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInvestigateInfo.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInvestigateInfo.setEndTime(now.getTime());
        }
        return investigateMapper.selectPlotByCondition(selectInvestigateInfo);
    }

    /**
     * 查询所有的图片信息
     */
    @Override
    public List<String> selectAllImagePath() {
        return investigateMapper.selectAllImagePath();
    }

    /**
     * 手动添加害虫信息
     * @param selectInvestigateInfo
     * @return
     */
    @Override
    public int updateManualTag(SelectInvestigateInfo selectInvestigateInfo) {
        InvestigateInfo investigateInfo = new InvestigateInfo();
        investigateInfo.setId(selectInvestigateInfo.getId());
        int longWingedAdult = selectInvestigateInfo.getLongWingedAdult();
        int shortWingedAdult = selectInvestigateInfo.getShortWingedAdult();
        int highInstarLarvae = selectInvestigateInfo.getHighInstarLarvae();
        int lowInstarLarvae = selectInvestigateInfo.getLowInstarLarvae();
        int other=selectInvestigateInfo.getOther();
        String tagManual="{";
        String otherTag="";
        String longWingedTag="";
        String shortWingedTag="";
        String highInstarLarvaeTag="";
        String lowInstarLarvaeTag="";
        int flag=0;
        if(other!=0){
            otherTag="\"0\":"+other;
        }
        if(longWingedAdult!=0){
            longWingedTag="\"1\":"+longWingedAdult;

        }

        if(highInstarLarvae!=0){
            highInstarLarvaeTag="\"2\":"+highInstarLarvae;

        }
        if(lowInstarLarvae!=0){
            lowInstarLarvaeTag="\"3\":"+lowInstarLarvae;

        }
        if(shortWingedAdult!=0){
            shortWingedTag="\"4\":"+shortWingedAdult;

        }
        if(!otherTag.equals("")){
            tagManual+=otherTag;
        }
        if(tagManual.length()>3 && (!longWingedTag.equals("") || !highInstarLarvaeTag.equals("") || !lowInstarLarvaeTag.equals("") ||!shortWingedTag.equals(""))){
            tagManual+=",";
        }
        if(!longWingedTag.equals("")){
            tagManual+=longWingedTag;
            flag=1;
        }
        if(flag==1 && (!highInstarLarvaeTag.equals("") || !lowInstarLarvaeTag.equals("") ||!shortWingedTag.equals(""))){
            tagManual+=",";
            flag=0;
        }
        if(!highInstarLarvaeTag.equals("") ){
            tagManual+=highInstarLarvaeTag;
            flag=1;
        }
        if(flag==1 && (!lowInstarLarvaeTag.equals("") ||!shortWingedTag.equals(""))){
            tagManual+=",";
            flag=0;
        }
        if(!lowInstarLarvaeTag.equals("") ){
            tagManual+=lowInstarLarvaeTag;
            flag=1;
        }
        if(flag==1 && !shortWingedTag.equals("")){
            tagManual+=",";
        }
        if(!shortWingedTag.equals("") ){
            tagManual+=shortWingedTag;
        }
        tagManual+="}";
        investigateInfo.setTagManual(tagManual);
        int count = investigateMapper.updateManualTag(investigateInfo);

        return count;
    }

    /**
     * 根据条件返回播报
     * @param selectInvestigateInfo
     * @return
     */
    @Override
    public List<BroadcastPlanthopperInfo> getBroadcastInfo(SelectInvestigateInfo selectInvestigateInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime=sdf.format(selectInvestigateInfo.getBeginTime());
        String endTime=sdf.format(selectInvestigateInfo.getEndTime());
        /* 计算时间间隔，按 天 存入 集合 */
        List<String> dates = MyDateUtil.calculateTimeInterval(startTime, endTime);

        /* 存放结果数据集 */
        List<BroadcastPlanthopperInfo> statistics = new ArrayList<>();
        for (String date : dates) {

            Calendar now =Calendar.getInstance();
            now.setTime(sdf.parse(date));
            now.set(Calendar.DATE,now.get(Calendar.DATE)+1);

            selectInvestigateInfo.setBeginTime(sdf.parse(date));
            selectInvestigateInfo.setEndTime(now.getTime());

            List<String> list = investigateMapper.selectTagByCondition(selectInvestigateInfo);
            PlanthopperNumType PlanthopperNumType = json2InsectType(list);

            BroadcastPlanthopperInfo insectStatistic = new BroadcastPlanthopperInfo();
            insectStatistic.setPlanthopperNumType(PlanthopperNumType);
            insectStatistic.setImgNum(list.size());
            insectStatistic.setDay(date);

            insectStatistic.setInsectTotalNumber(PlanthopperNumType.getLongWingedAdult() + PlanthopperNumType.getShortWingedAdult() + PlanthopperNumType.getHighInstarLarvae() + PlanthopperNumType.getLowInstarLarvae() + PlanthopperNumType.getOther());
            int average = 0;
            if (insectStatistic.getImgNum() > 0) {
                average = insectStatistic.getInsectTotalNumber() / insectStatistic.getImgNum() * 100;
            }
            insectStatistic.setAverageInsectTotalNumber(average);
            insectStatistic.setLevel(judgmentLevel(average));
            statistics.add(insectStatistic);
        }
        return statistics;
    }

    @Override
    public ReturnBroadcastHundred getBroadcastHundred(SelectInvestigateInfo selectInvestigateInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime=sdf.format(selectInvestigateInfo.getBeginTime());
        String endTime=sdf.format(selectInvestigateInfo.getEndTime());
        /* 计算时间间隔，按 天 存入 集合 */
        List<String> dates = MyDateUtil.calculateTimeInterval(startTime, endTime);
        List<String> dateList=new ArrayList<>();

        List<List<Integer>> hundredNum=new ArrayList<>();
        List<Integer> aveLongWingedAdultList=new ArrayList<>();
        List<Integer> aveHighInstarLarvaeList=new ArrayList<>();
        List<Integer> aveLowInstarLarvaeList=new ArrayList<>();
        List<Integer> aveShortWingedAdultList=new ArrayList<>();
        hundredNum.add(aveLongWingedAdultList);
        hundredNum.add(aveHighInstarLarvaeList);
        hundredNum.add(aveLowInstarLarvaeList);
        hundredNum.add(aveShortWingedAdultList);

        ReturnBroadcastHundred returnBroadcastHundred = new ReturnBroadcastHundred();

        List<String> names = planthopperMapper.selectPlanthopper();
        returnBroadcastHundred.setName(names);

        for (String date : dates) {
            dateList.add(date);
            Calendar now =Calendar.getInstance();
            now.setTime(sdf.parse(date));
            now.set(Calendar.DATE,now.get(Calendar.DATE)+1);

            selectInvestigateInfo.setBeginTime(sdf.parse(date));
            selectInvestigateInfo.setEndTime(now.getTime());

            List<String> list = investigateMapper.selectTagByCondition(selectInvestigateInfo);
            if(list.size()==0){
                hundredNum.get(0).add(0);
                hundredNum.get(1).add(0);
                hundredNum.get(2).add(0);
                hundredNum.get(3).add(0);
            }else {
                PlanthopperNumType  insectType = json2InsectType(list);

                int aveLongWingedAdult = Math.round(insectType.getLongWingedAdult() * 300 / list.size());
                int aveHighInstarLarvae = Math.round(insectType.getHighInstarLarvae() * 300 / list.size());
                int aveLowInstarLarvae = Math.round(insectType.getLowInstarLarvae() * 300 / list.size());
                int aveShortWingedAdult = Math.round(insectType.getShortWingedAdult() * 300 / list.size());
                hundredNum.get(0).add(aveLongWingedAdult);
                hundredNum.get(1).add(aveHighInstarLarvae);
                hundredNum.get(2).add(aveLowInstarLarvae);
                hundredNum.get(3).add(aveShortWingedAdult);
            }


        }

        returnBroadcastHundred.setHundredNum(hundredNum);
        returnBroadcastHundred.setDateList(dateList);
        return returnBroadcastHundred;
    }


    /**
     * 从数据库的形式加入一个insceptType字段，方便前端获取数据
     * @param investigateInfoList
     * @return
     */
    public static List<ReturnInvestigateInfo>  getReturnInfo(List<InvestigateInfo> investigateInfoList ){
        List<ReturnInvestigateInfo> returnInvestigateInfosList = new ArrayList<>();
        for (InvestigateInfo investigateInfo : investigateInfoList) {

            ReturnInvestigateInfo returnInvestigateInfos = new ReturnInvestigateInfo();
            returnInvestigateInfos.setInvestigator(investigateInfo.getInvestigator());
            returnInvestigateInfos.setId(investigateInfo.getId());
            returnInvestigateInfos.setImagePath(investigateInfo.getImagePath());
            returnInvestigateInfos.setDiseaseType(investigateInfo.getDiseaseType());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            returnInvestigateInfos.setShootingTime(sdf.format(investigateInfo.getShootingTime()));
            returnInvestigateInfos.setUploadTime(sdf.format(investigateInfo.getUploadTime()));
            //returnInvestigateInfos.setShootingTime(investigateInfo.getShootingTime());
            //returnInvestigateInfos.setUploadTime(investigateInfo.getUploadTime());
            returnInvestigateInfos.setWeather(investigateInfo.getWeather());
            returnInvestigateInfos.setWindpower(investigateInfo.getWindpower());
            returnInvestigateInfos.setTemperature(investigateInfo.getTemperature());
            returnInvestigateInfos.setHumidity(investigateInfo.getHumidity());
            returnInvestigateInfos.setProvince(investigateInfo.getProvince());
            returnInvestigateInfos.setCity(investigateInfo.getCity());
            returnInvestigateInfos.setDistrict(investigateInfo.getDistrict());
            returnInvestigateInfos.setPlot(investigateInfo.getPlot());
            returnInvestigateInfos.setInvestigator(investigateInfo.getInvestigator());
            returnInvestigateInfos.setShootingEquipment(investigateInfo.getShootingEquipment());
            if(investigateInfo.getTag()==null ||  investigateInfo.getTag().equals("") ){
                investigateInfo.setTag("{}");
            }
            returnInvestigateInfos.setTag(investigateInfo.getTag());
            if(investigateInfo.getTagManual()==null || investigateInfo.getTagManual().equals("") ){
                investigateInfo.setTagManual("{}");
            }
            returnInvestigateInfos.setTagManual(investigateInfo.getTagManual());
            returnInvestigateInfos.setOriginalFileName(investigateInfo.getOriginalFileName());
            returnInvestigateInfos.setThumPath(investigateInfo.getThumPath());
            returnInvestigateInfos.setResultPath(investigateInfo.getResultPath());
            returnInvestigateInfos.setPhone(investigateInfo.getPhone());
            returnInvestigateInfos.setEarlyOrLateRice(investigateInfo.getEarlyOrLateRice());
            returnInvestigateInfos.setVarieties(investigateInfo.getVarieties());
            returnInvestigateInfos.setGrowthPeriod(investigateInfo.getGrowthPeriod());
            //System.out.println(returnInvestigateInfos.toString());
            PlanthopperNumType PlanthopperNumType = json2InsectTypeForOne(returnInvestigateInfos.getTag());
            returnInvestigateInfos.setPlanthopperNumType(PlanthopperNumType);
            PlanthopperNumType PlanthopperNumTypeManual = json2InsectTypeForOne(returnInvestigateInfos.getTagManual());
            returnInvestigateInfos.setPlanthopperNumTypeManual(PlanthopperNumTypeManual);
            returnInvestigateInfosList.add(returnInvestigateInfos);
        }
        return returnInvestigateInfosList;
    }

    /**
     * 判断预警等级 0是最低 4 最高
     *
     * @param quantity 数量
     * @return 等级
     */
    public static int judgmentLevel(Integer quantity) {
        if ((quantity < 1000) && (quantity > 0)) {
            return 1;
        }
        if ((quantity >= 1000) && (quantity < 3000)) {
            return 2;
        }
        if ((quantity >= 3000) && (quantity < 8000)) {
            return 3;
        }
        if (quantity >= 8000) {
            return 4;
        }
        return 0;
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'ccfs': 1,
     * 'glrc': 2,
     * 'dlrc': 3,
     * 'dcfs': 4,
     *
     * @param tag tag
     * @return InsectType类型
     */
    public static PlanthopperNumType json2InsectTypeForOne(String tag) {

        int longWingedAdult = 0;

        int shortWingedAdult = 0;

        int highInstarLarvae = 0;

        int lowInstarLarvae = 0;

        int other = 0;
        //System.out.println(tag);
        JSONObject totalNum = JSON.parseObject(tag);
        if (totalNum.containsKey("1")) {
            longWingedAdult += (Integer) totalNum.get("1");
        }
        if (totalNum.containsKey("4")) {
            shortWingedAdult += (Integer) totalNum.get("4");
        }
        if (totalNum.containsKey("2")) {
            highInstarLarvae += (Integer) totalNum.get("2");
        }
        if (totalNum.containsKey("3")) {
            lowInstarLarvae += (Integer) totalNum.get("3");
        }
        if (totalNum.containsKey("0")) {
            other += (Integer) totalNum.get("0");
        }

        return new PlanthopperNumType(longWingedAdult, shortWingedAdult, highInstarLarvae, lowInstarLarvae, other);
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * 'ccfs': 1,
     * 'glrc': 2,
     * 'dlrc': 3,
     * 'dcfs': 4,
     *
     * @param list list列表
     * @return InsectType类型
     */
    public static PlanthopperNumType json2InsectType(List<String> list) {

        int longWingedAdult = 0;

        int shortWingedAdult = 0;

        int highInstarLarvae = 0;

        int lowInstarLarvae = 0;

        int other = 0;

        for (String s : list) {
            if(s!=null) {
                JSONObject totalNum = JSON.parseObject(s);
                if (totalNum.containsKey("1")) {
                    longWingedAdult += (Integer) totalNum.get("1");
                }
                if (totalNum.containsKey("4")) {
                    shortWingedAdult += (Integer) totalNum.get("4");
                }
                if (totalNum.containsKey("2")) {
                    highInstarLarvae += (Integer) totalNum.get("2");
                }
                if (totalNum.containsKey("3")) {
                    lowInstarLarvae += (Integer) totalNum.get("3");
                }
                if (totalNum.containsKey("0")) {
                    other += (Integer) totalNum.get("0");
                }
            }
        }
        return new PlanthopperNumType(longWingedAdult, shortWingedAdult, highInstarLarvae, lowInstarLarvae, other);
    }
}
